package com.lujianfei.mqtt

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.lujianfei.mqtt.callback.MqttServiceCallBack
import com.lujianfei.mqtt.ext.toast
import com.lujianfei.mqtt.service.MQTTService
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "MainActivity"
    }

    private var mMQTTService: MQTTService?= null
    private var mBound = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btnSend.setOnClickListener {
            publish()
        }
    }

    private fun publish() {
        if (editInput.text.isNullOrEmpty()) {
            toast("请输入内容")
            return
        }
        mMQTTService?.publish(editInput.text.toString())
    }

    override fun onStart() {
        super.onStart()
        Log.i(TAG,"onStart")
        bindService(Intent(this,MQTTService::class.java),
                mConnection,
                Context.BIND_AUTO_CREATE)
    }

    override fun onStop() {
        super.onStop()
        Log.i(TAG,"onStop")
        if (mBound) {
            unbindService(mConnection)
            mBound = false
        }
    }
    private val mConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            mBound = false
            Log.i(TAG,"onServiceDisconnected $name")
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.i(TAG,"onServiceConnected $name $service")
            if (service is MQTTService.CustomBinder) {
                mMQTTService = service.service
                mMQTTService?.setOnCallback(mMqttServiceCallBack)
                mBound = true
            }
        }
    }


    private val mMqttServiceCallBack = object : MqttServiceCallBack {
        override fun onMessageReceive(message: String?) {
            Log.i(TAG,"onMessageReceive $message")
            txtInfo.append("$message\r\n")
        }
    }
}
